package com.can.utils;

import com.can.common.constant.ShiroConstants;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * @Desription 密码加密辅助类
 * @Author can
 * @Date 2018/9/28
 * @Version 1.0
 */
public class PasswordHelper {

    /**
     * 随机生成 salt 需要指定 它的字符串的长度
     * @return salt
     */
    public static String generateSalt() {
        //一个Byte占两个字节
        int byteLen = ShiroConstants.random_salt_length >> 1;
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        return secureRandom.nextBytes(byteLen).toHex();
    }

    /**
     * 获取密码盐
     * @param salt          盐
     * @param randomSalt    随机盐
     * @return
     */
    public static ByteSource credentialsSalt(String salt,String randomSalt){
        return ByteSource.Util.bytes(salt + randomSalt);
    }

    /**
     * 获取加密后的密码，需要指定 hash迭代的次数
     *
     * @param password      需要加密的密码
     * @param salt          盐
     * @param randomSalt    随机盐
     * @return 加密后的密码
     */
    public static String encryptPassword(String password, String salt, String randomSalt) {
        SimpleHash hash = new SimpleHash(ShiroConstants.HASH_ALGORITHM_NAME, password, credentialsSalt(salt, randomSalt),ShiroConstants.HASH_ITERATIONS);
        return hash.toString();
    }
}
